/**   
 * @Title: ContextMg.java 
 * CopyRight(c)2010-DMX 
 */
package com.dmx.fw.resource;

import java.util.HashMap;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import com.dmx.fw.exception.GeneralException;
import com.dmx.fw.exception.GeneralExceptionHandler;



/**应用上下文环境管理，参数信息来源sytem配置文件
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2004</p>
 * <p>Company: </p>
 * @author not attributable
 * @version 1.0
 */

public class ContextMg {

	private static HashMap contextMap = new HashMap();
	
	private static String DEFAULT_CONTEXT_NAME = "DEFAULT_CONTEXT_NAME";
	
    /**
     * 获得上下文环境
     * @return
     * @throws java.lang.Exception
     */
    public static Context getContext(JndiMetaData jmd)throws GeneralException {
        String contextName = DEFAULT_CONTEXT_NAME;
        if (jmd==null){
        	jmd = new JndiMetaData();
        	jmd.setFactoryInitial(SystemProperties.getInstance().getInitialContextFactory());
        	jmd.setProviderUrl(SystemProperties.getInstance().getProviderUrl());
        	jmd.setSecurityPrincipal(SystemProperties.getInstance().getSecurityPrincipal());
        	jmd.setSecurityCredentials(SystemProperties.getInstance().getSecurityCredentials());
        }else{
        	contextName = jmd.getFactoryInitial() + jmd.getProviderUrl();
        }
	
        if (contextMap.get(contextName)==null){
     	   synchronized (contextMap){
     		   Context context = initialContext(jmd);
     		   if (context!=null){
     			   contextMap.put(contextName,context);
     		   }
            }
        }
        return (Context)contextMap.get(contextName);
     }

    /**
     * 初始化上下文环境
     * @throws java.lang.Exception
     */
    private static Context initialContext(JndiMetaData jmd) throws GeneralException{
        Context context = null;

        try{        
	        if (jmd.getFactoryInitial()==null || "".equals(jmd.getFactoryInitial())){
	        	context = new InitialContext();
	        }else{
	        	Properties p = new Properties();      
	
		        p.put(Context.INITIAL_CONTEXT_FACTORY, jmd.getFactoryInitial());
		        p.put(Context.PROVIDER_URL, jmd.getProviderUrl());
		        if(jmd.getSecurityPrincipal() != null && !"".equals(jmd.getSecurityPrincipal())){
		            p.put(Context.SECURITY_PRINCIPAL, jmd.getSecurityPrincipal());
		            if(jmd.getSecurityCredentials() == null){
		            	p.put(Context.SECURITY_CREDENTIALS, "");
		            }else{
		            	p.put(Context.SECURITY_CREDENTIALS, jmd.getSecurityPrincipal());
		            }            
		        }
		        context = new InitialContext(p);
	        }			
        }catch(NamingException e){
            GeneralExceptionHandler.Handle(e);
        }
        return context;
    }

}